package flex.cc.basicinformation.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderConfigDao;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderDao;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderConfigEntity;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderEntity;
import flex.cc.basicinformation.vo.ValueAddedServiceProviderVo;
import flex.cc.basicinformation.service.ValueAddedServiceProviderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wkangle
 * @className ValueAddedServiceProviderServiceImpl
 * @description 增值服务服务商service
 * @time 2022-02-24 15:03:56
 */
@Service("valueAddedServiceProviderService")
public class ValueAddedServiceProviderServiceImpl extends ServiceImpl<ValueAddedServiceProviderDao, ValueAddedServiceProviderEntity> implements ValueAddedServiceProviderService {
    private static final Logger logger = LoggerFactory.getLogger(ValueAddedServiceProviderServiceImpl.class);

    @Resource
    private ValueAddedServiceProviderDao valueAddedServiceProviderDao;
    @Resource
    private ValueAddedServiceProviderConfigDao valueAddedServiceProviderConfigDao;


    /**
     * @param vo 查询参数
     * @return
     * @description 查询增值服务服务商
     * @author wkangle
     * @time 2022/02/25 0025 13:48
     * @exception/throws
     */
    @Override
    public IPage<ValueAddedServiceProviderVo> queryListWithPage(ValueAddedServiceProviderVo vo) {
        Page<ValueAddedServiceProviderVo> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        String status = vo.getStatus();
        String[] statusSplit = PublicUtil.isNotEmpty(status) ? status.split(",") : null;
        vo.setStatusList(statusSplit);
        String serviceType = vo.getServiceType();
        String[] serviceTypeSplit = PublicUtil.isNotEmpty(serviceType) ? serviceType.split(",") : null;
        vo.setServiceTypeList(serviceTypeSplit);
        IPage<ValueAddedServiceProviderVo> pageData = valueAddedServiceProviderDao.queryListWithPage(page, vo);
        return pageData;
    }

    /**
     * @param params 查询参数
     * @return
     * @description 根据参数查询增值服务服务商接口配置信息
     * @author wkangle
     * @time 2022-02-24 15:00:03
     * @exception/throws
     */
    @Override
    public ValueAddedServiceProviderEntity getOneByParams(Map<String, Object> params) {
        return valueAddedServiceProviderDao.getOneByParams(params);
    }

    /**
     * @param id 增值服务商主键
     * @param status
     * @return
     * @description 修改增值服务商状态【2.2-服务包配置需求】
     * @author wkangle
     * @time 2022-02-25 13:38:47
     * @exception/throws
     */
    @Override
    public Map<String, String> switchStatus(Long id, String status) {
        Map<String, String> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        ValueAddedServiceProviderEntity oneByParams = valueAddedServiceProviderDao.getOneByParams(params);

        if (PublicUtil.isEmpty(oneByParams)) {
            result.put("code", "0001");
            result.put("message", "增值服务商不存在");
            return result;
        }
        if ("1".equals(status)) { // 启用
            String dbStatus = oneByParams.getStatus();
            if ("1".equals(dbStatus)) {
                result.put("code", "0001");
                result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")已是启用状态");
                return result;
            } else {
                try {
                    oneByParams.setStatus("1");
                    valueAddedServiceProviderDao.updateById(oneByParams);

                    result.put("code", "0000");
                    result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")启用成功");
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    result.put("code", "0001");
                    result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")启用失败，原因：" + e.getMessage());
                    return result;
                }
            }
        } else { // 禁用
            String dbStatus = oneByParams.getStatus();
            if ("0".equals(dbStatus)) {
                result.put("code", "0001");
                result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")已是禁用状态");
                return result;
            } else {
                try {
                    oneByParams.setStatus("0");
                    valueAddedServiceProviderDao.updateById(oneByParams);

                    result.put("code", "0000");
                    result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")禁用成功");
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    result.put("code", "0001");
                    result.put("message", "增值服务商(" + oneByParams.getServiceName() + ")禁用失败，原因：" + e.getMessage());
                    return result;
                }
            }
        }
    }

    /**
     * @param loginAuthDto 当前操作人
     * @param vo           增值服务商信息
     * @return
     * @description 新增/编辑增值服务商，及增值服务商接口配置信息【2.2-服务包配置需求】 TODO
     * @author wkangle
     * @time 2022/02/25 0025 17:03
     * @exception/throws
     */
    @Override
    public Map<String, String> saveValueAddedServiceProvider(LoginAuthDto loginAuthDto, ValueAddedServiceProviderVo vo) {
        Map<String, String> result = new HashMap<>();

        if (PublicUtil.isEmpty(vo.getId())) { // id为空，新增
            try {
                Date currentDate = new Date();
                List<ValueAddedServiceProviderEntity> list = valueAddedServiceProviderDao.selectValueAddedServiceProviderName(vo);
                if (list != null && list.size() > 0) { // 新增，如果大于0说明有重复的
                    logger.info("{} 增值服务商【{}】已经存在", currentDate, vo.getServiceName());
                    result.put("code", "0001");
                    result.put("message", "增值服务商【" + vo.getServiceName() + "】已经存在");
                    return result;
                } else {
                    List<ValueAddedServiceProviderConfigEntity> valueAddedServiceProviderConfigEntityList = vo.getValueAddedServiceProviderConfigEntityList();
                    String index = removaDuplicate(valueAddedServiceProviderConfigEntityList);
                    if (!"0".equals(index)) {
                        String type = valueAddedServiceProviderConfigEntityList.get(Integer.valueOf(index) - 1).getType();
                        logger.info("{} 您所选择的接口类型/密钥类型【{}】重复", currentDate, type);
                        result.put("code", "0001");
                        result.put("message", "您所选择的接口类型/密钥类型【" + type + "】重复");
                        return result;
                    }
                    ValueAddedServiceProviderEntity dbEntity = new ValueAddedServiceProviderEntity();
                    dbEntity.setServiceName(vo.getServiceName());
                    dbEntity.setApiCode(vo.getApiCode());
                    dbEntity.setServiceType(vo.getServiceType());
                    dbEntity.setStatus("1"); // 0-禁用，默认1-启用

                    dbEntity.setCreater(loginAuthDto.getUserCode());
                    dbEntity.setCreateTime(currentDate);
                    dbEntity.setUpdater(loginAuthDto.getUserCode());
                    dbEntity.setUpdateTime(currentDate);
                    valueAddedServiceProviderDao.insert(dbEntity);

                    Long spid = dbEntity.getId();
                    for (ValueAddedServiceProviderConfigEntity valueAddedServiceProviderConfigEntity : valueAddedServiceProviderConfigEntityList) {
                        valueAddedServiceProviderConfigEntity.setSpid(spid);
                        valueAddedServiceProviderConfigEntity.setCreater(loginAuthDto.getUserCode());
                        valueAddedServiceProviderConfigEntity.setCreateTime(currentDate);
                        valueAddedServiceProviderConfigEntity.setUpdater(loginAuthDto.getUserCode());
                        valueAddedServiceProviderConfigEntity.setUpdateTime(currentDate);
                        valueAddedServiceProviderConfigDao.insert(valueAddedServiceProviderConfigEntity);
                    }
                    result.put("code", "0000");
                    result.put("message", "新增成功");
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", "00001");
                result.put("message", "新增失败： + " + e.getMessage());
                return result;
            }
        } else { // id不为空，编辑
            try {
                Date currentDate = new Date();
                // 查询一个渠道商
                Map<String, Object> vaspParams = new HashMap<>();
                vaspParams.put("id", vo.getId());
                ValueAddedServiceProviderEntity valueAddedServiceProviderEntity = this.getOneByParams(vaspParams);

                List<ValueAddedServiceProviderEntity> list = valueAddedServiceProviderDao.selectValueAddedServiceProviderName(vo);

                boolean remove = list.remove(valueAddedServiceProviderEntity);

                if (list != null && list.size() > 0) {
                    logger.info("{} 增值服务商【{}】已经存在", currentDate, vo.getServiceName());
                    result.put("code", "0001");
                    result.put("message", "增值服务商【" + vo.getServiceName() + "】已经存在");
                    return result;
                } else {
                    List<ValueAddedServiceProviderConfigEntity> valueAddedServiceProviderConfigEntityList = vo.getValueAddedServiceProviderConfigEntityList();
                    String index = removaDuplicate(valueAddedServiceProviderConfigEntityList);
                    if (!"0".equals(index)) {
                        String type = valueAddedServiceProviderConfigEntityList.get(Integer.valueOf(index) - 1).getType();
                        logger.info("{} 您所选择的接口类型/密钥类型【{}】重复", currentDate, type);
                        result.put("code", "0001");
                        result.put("message", "您所选择的接口类型/密钥类型【" + type + "】重复");
                        return result;
                    }

                    // 查询一个增值服务商
                    Map<String, Object> valueAddedSserviceProviderlParams = new HashMap<>();
                    valueAddedSserviceProviderlParams.put("id", vo.getId());
                    ValueAddedServiceProviderEntity dbEntity = valueAddedServiceProviderDao.getOneByParams(valueAddedSserviceProviderlParams);
                    dbEntity.setServiceName(vo.getServiceName());
                    dbEntity.setServiceType(vo.getServiceType());
                    dbEntity.setStatus(vo.getStatus());

                    dbEntity.setUpdater(loginAuthDto.getUserCode());
                    dbEntity.setUpdateTime(currentDate);
                    valueAddedServiceProviderDao.updateById(dbEntity);

                    Long spid = dbEntity.getId();
                    // 删除已有的，将新的重新保存
                    int deleteBySpid = valueAddedServiceProviderConfigDao.deleteBySpid(spid);
                    for (ValueAddedServiceProviderConfigEntity valueAddedServiceProviderConfigEntity : valueAddedServiceProviderConfigEntityList) {
                        valueAddedServiceProviderConfigEntity.setSpid(spid);
                        valueAddedServiceProviderConfigEntity.setCreater(loginAuthDto.getUserCode());
                        valueAddedServiceProviderConfigEntity.setCreateTime(currentDate);
                        valueAddedServiceProviderConfigEntity.setUpdater(loginAuthDto.getUserCode());
                        valueAddedServiceProviderConfigEntity.setUpdateTime(currentDate);
                        valueAddedServiceProviderConfigDao.insert(valueAddedServiceProviderConfigEntity);
                    }
                    result.put("code", "0000");
                    result.put("message", "修改成功");
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result.put("code", "0001");
                result.put("message", "修改失败： " + e.getMessage());
                return result;
            }
        }
    }

    /**
     * @param id 增值服务商主键id
     * @return
     * @description 根据增值服务商主键id查询一个，用于修改回显
     * @author wkangle
     * @time 2022/02/28 0028 10:28
     * @exception/throws
     */
    @Override
    public ValueAddedServiceProviderVo queryOne(Long id) {
        Map<String, Object> params = new HashMap();
        params.put("id", id);
        ValueAddedServiceProviderEntity entity = this.getOneByParams(params);
        ValueAddedServiceProviderVo vo = new ValueAddedServiceProviderVo();
        vo.setId(entity.getId());
        vo.setServiceName(entity.getServiceName());
        vo.setApiCode(entity.getApiCode());
        vo.setServiceType(entity.getServiceType());
        vo.setStatus(entity.getStatus());

        vo.setIsDelete(entity.getIsDelete());
        vo.setCreater(entity.getCreater());
        vo.setCreateTime(entity.getCreateTime());
        vo.setUpdater(entity.getUpdater());
        vo.setUpdateTime(entity.getUpdateTime());

        params.put("id", null);
        params.put("spid", id);
        List<ValueAddedServiceProviderConfigEntity> list = valueAddedServiceProviderConfigDao.queryByParams(params);
        vo.setValueAddedServiceProviderConfigEntityList(list);
        return vo;
    }

    /**
     * @param serviceName 增值服务商名称
     * @param id 主键id
     * @return
     * @description 校验增值服务商名称是否重复
     * @author wkangle
     * @time 2022/02/28 0028 11:10
     * @exception/throws
     */
    @Override
    public String checkServiceName(String serviceName, String id) {
        // 查询一个渠道商
        Map<String, Object> vaspParams = new HashMap<>();
        vaspParams.put("id", id);
        ValueAddedServiceProviderEntity valueAddedServiceProviderEntity = this.getOneByParams(vaspParams);

        ValueAddedServiceProviderEntity entity = new ValueAddedServiceProviderEntity();
        entity.setServiceName(serviceName);
        List<ValueAddedServiceProviderEntity> list = valueAddedServiceProviderDao.selectValueAddedServiceProviderName(entity);

        boolean remove = list.remove(valueAddedServiceProviderEntity);

        String result="";
        if(list != null && list.size() > 0) {
            result = "1";
        } else {
            result = "0";
        }
        return result;
    }

    /**
     * @param apiCode 增值服务商标识
     * @param id      主键id
     * @return
     * @description 校验增值服务商标识是否重复
     * @author wkangle
     * @time 2022-03-10 09:14:18
     * @exception/throws
     */
    @Override
    public String checkApiCode(String apiCode, String id) {
        // 查询一个渠道商
        Map<String, Object> vaspParams = new HashMap<>();
        vaspParams.put("id", id);
        ValueAddedServiceProviderEntity valueAddedServiceProviderEntity = this.getOneByParams(vaspParams);

        ValueAddedServiceProviderEntity entity = new ValueAddedServiceProviderEntity();
        entity.setApiCode(apiCode);
        List<ValueAddedServiceProviderEntity> list = valueAddedServiceProviderDao.selectValueAddedServiceProviderName(entity);

        boolean remove = list.remove(valueAddedServiceProviderEntity);

        String result="";
        if(list != null && list.size() > 0) {
            result = "1";
        } else {
            result = "0";
        }
        return result;
    }

    public String removaDuplicate(List<ValueAddedServiceProviderConfigEntity> list) {
        String temp = "";
        for (int i = 0; i < list.size() - 1; i++) {
            ValueAddedServiceProviderConfigEntity valueAddedServiceProviderConfigEntity = list.get(i);
            temp = valueAddedServiceProviderConfigEntity.getType();
            for (int j = i + 1; j < list.size(); j++) {
                if (temp.equals(list.get(j).getType())) {
                    System.out.println("第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
                    logger.info("第" + (i + 1) + "个跟第" + (j + 1) + "个重复，值是：" + temp);
                    return (i + 1) + "";
                }
            }
        }
        return "0";
    }

	/**
	 * @author R
	 * 2022年03月02日 10:51:16
	 * @desc 查询所有有效的服务商  新增/修改 服务包内容页面  服务商下拉列表
	 */
    public List<ValueAddedServiceProviderEntity> queryValidProviderList(){
    	return valueAddedServiceProviderDao.queryValidProviderList();
    }

    /**
	 * @author WANGCONG
	 * 2022年3月3日下午16:31:26
	 * @desc 查询所有服务商下拉列表
	 */
	@Override
	public List<ValueAddedServiceProviderEntity> queryProviderList() {
		return valueAddedServiceProviderDao.queryProviderList();
	}
}
